<template>
  <div class="user-container">
    <div class="search" style="display: flex;justify-content: space-between;">
    <el-form :model="searchOptions"  style="text-align: left;" ref="searchForm">
      <el-select v-model="searchOptions.deptId" size="small" placeholder="选择部门" clearable>
        <i slot="prefix" class="el-input__icon el-icon-coordinate"></i>
        <el-option v-for="item in deptOptions" :key="item.id" :label="item.deptname" :value="item.id"></el-option>
      </el-select>
      <el-input v-model="searchOptions.key" placeholder="输入姓名" size="small" style="width: 150px;"><i slot="prefix" class="el-input__icon el-icon-user"></i></el-input>
      <el-select v-model="searchOptions.state" size="small" placeholder="选择用户状态" clearable style="width: 150px;" >
        <i slot="prefix" class="el-input__icon el-icon-coordinate"></i>
        <el-option v-for="item in stateOptions" :key="item.id" :label="item.statename" :value="item.id"></el-option>
      </el-select>
      <el-button type="primary" size="small" @click="search" icon="el-icon-search">搜索</el-button>
      <el-button type="infor" size="small" native-type="reset" @click="searchReset" icon="el-icon-refresh">重置</el-button>
    </el-form >
    <div>
      <el-button type="warning" size="small" @click="isAddDialog = true" icon="el-icon-plus">添加</el-button>
    </div>
  </div>
    <el-table
      :data="tableData"
      v-loading="loading"
      border
      style="width: 100%;">
      <el-table-column label="序号" width="100">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="工号"></el-table-column>
      <el-table-column prop="name" label="姓名" width="150"></el-table-column>
      <el-table-column prop="gender" label="性别" width="100">
        <template slot-scope="scope">
          <span>{{ (scope.row.gender==='0')?'男':'女' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号码" width="140"></el-table-column>
      <el-table-column prop="departmentName" label="部门" width="200"></el-table-column>
      <el-table-column prop="state" label="状态" width="90" align="center">
        <template slot-scope="scope">
          <el-tag :type="(scope.row.state===1)?'':(scope.row.state===2)?'success':(scope.row.state===3)?'warning':'info'">
            {{ (scope.row.state===1)?'全职':(scope.row.state==2)?'实习':(scope.row.state==3)?'兼职':'离职' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <div style="text-align: center;display: flex;justify-content: space-around" slot-scope="scope">
          <el-link type="primary" icon="el-icon-edit-outline" :underline="false" @click="openUserEditor(scope.row.id)">编辑</el-link>
          <el-popconfirm confirmButtonText="确定" cancelButtonText="取消" icon="el-icon-warning-outline" iconColor="red" title="是否确定删除？"
                         @onConfirm="deleteUser(scope.row.id)" @onCancel="">
            <el-link type="danger" size="mini" icon="el-icon-delete" :underline="false" slot="reference">删除</el-link>
          </el-popconfirm>
        </div>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      class="lay-pagination"
      layout="total, prev, pager, next, jumper"
      :current-page.sync="pagination.currentPage"
      :page-size="pagination.pageSize"
      :total="pagination.total"
      @current-change="handleCurrentChange">
    </el-pagination>


    <!-- 创建新增用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="isAddDialog"
      width="40%">
      <el-form
        ref="addUserForm"
        :rules="userRules"
        :model="addUser"
        label-width="100px">
        <el-form-item label="真实姓名" prop="name">
          <el-input v-model="addUser.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="addUser.phone"></el-input>
        </el-form-item>
        <el-form-item label="所在部门" prop="deptIds">
          <el-cascader
            v-model="addUser.deptIds"
            :options="deptOptions"
            :props="{ checkStrictly: true }"
            clearable
            style="width: 100%"></el-cascader>
        </el-form-item>
        <el-form-item label="用户角色" prop="roleIds">
          <el-select
            v-model="addUser.roleIds"
            multiple
            filterable
            default-first-option
            style="width: 100%"
            placeholder="请选择用户角色">
            <el-option
              style="text-align: left;"
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户状态" prop="state">
          <el-radio-group v-model="addUser.state" size="small" style="width: 100%;text-align: left">
            <el-radio :label="item.id" v-for="item in stateOptions" :key="item.id" border>{{ item.statename }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetAddUser">清空</el-button>
        <el-button type="primary" @click="submitAddUser">确定</el-button>
      </div>
    </el-dialog>

    <!-- 创建编辑用户对话框 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="isEditorDialog"
      width="40%">
      <el-form
        ref="editorUserForm"
        :rules="userRules"
        :model="editorUser"
        label-width="100px">
        <el-form-item label="真实姓名" prop="name">
          <el-input v-model="editorUser.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="editorUser.phone"></el-input>
        </el-form-item>
        <el-form-item label="所在部门" prop="deptIds">
          <el-cascader
            v-model="editorUser.deptIds"
            :options="deptOptions"
            :props="{ checkStrictly: true }"
            clearable
            style="width: 100%"></el-cascader>
        </el-form-item>
        <el-form-item label="用户角色" prop="roleIds">
          <el-select
            v-model="editorUser.roleIds"
            multiple
            filterable
            default-first-option
            style="width: 100%"
            placeholder="请选择用户角色">
            <el-option
              style="text-align: left;"
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户状态" prop="state">
          <el-radio-group v-model="editorUser.state" size="small" style="width: 100%;text-align: left">
            <el-radio :label="item.id" v-for="item in stateOptions" :key="item.id" border>{{ item.statename }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitEditorUser">更新</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { getUserList, getUserById, insertUser, updateUser, deleteUserById } from '@/api/user'
  import { getSelectRole } from "@/api/role"

  export default {
      name: "sysUser",
      data() {
        return {
          loading: true,
          searchOptions: {
            deptId: '',
            key: '',
            state: ''
          },
          deptOptions: [
            {id: 1, deptname: '人事部'},
            {id: 2, deptname: '开发部'},
            {id: 3, deptname: '调研部'}
            ],
          stateOptions: [
            {id: 1, statename: '全职'},
            {id: 2, statename: '实习'},
            {id: 3, statename: '兼职'},
            {id: 0, statename: '离职'}

          ],
          tableData: [
          //   {
          //   id: '1704220325',
          //   name: '林思浩',
          //   gender: 0,
          //   phone: '15089132169',
          //   departmentName: '开发部',
          //   state: 1
          // }
          ],
          pagination: {
            currentPage: 1,
            pageSize: 7,
            total: 150
          },
          isAddDialog: false,
          isEditorDialog: false,
          userRules: {
            name: [{required: true, message: '请填写真实姓名', trigger: 'blur'}],
            phone: [{required: true, message: '请填写手机号码', trigger: 'blur'}],
            deptIds: [{required: true, message: '请填写所在部门', trigger: 'blur'}],
            roleIds: [{required: true, message: '请填写用户角色', trigger: 'blur'}],
            state: [{required: true, message: '请填写用户状态', trigger: 'blur'}]
          },
          addUser: {
            name: '',
            phone: '',
            deptIds: '',
            roleIds: '',
            state: ''
          },
          editorUser: {
            name: '',
            phone: '',
            deptIds: '',
            roleIds: '',
            state: ''
          },
          roleOptions : [
            // {value: '1',label: '系统管理员'}
          ],
          deptOptions : [
          // {value: '1',label: '研发部'}
          ]
        }
      },
      methods: {
        //条件查询
        search() {
          this.pagination.currentPage = 1
          this.getUserList()
        },
        //重置条件查询
        searchReset() {
          this.searchOptions = {
            deptId: '',
            key: '',
            state: ''
          }
        },
        //获取用户列表
        getUserList() {
          let data = this.searchOptions
          data.page = this.pagination.currentPage
          this.loading = false;
          getUserList(data).then(res=>{
            let data = res.data.data.user_list;
            this.tableData = data.list;
            this.pagination.total = data.total;
            this.pagination.pageSize = data.pageSize
          })
        },
        //打开编辑用户框
        openUserEditor(id) {
          getUserById(id).then(res=>{
            if(res.data.code === 200) {
              this.isEditorDialog = true
              let user = res.data.data.user
              this.editorUser = {
                id: user.id,
                name: user.name,
                phone: user.phone,
                deptIds: user.deptIds,
                roleIds: user.roleIds,
                state: user.state
              }
            }
          })
        },
        //删除用户
        deleteUser(id) {
          deleteUserById(id).then(res=>{
            if(res.data.code === 200) {
              this.$message.success('删除成功')
              this.getUserList()
            }
          })
        },
        //监听当前页码，并发起请求
        handleCurrentChange(page) {
          this.getUserList()
        },
        //提交添加用户
        submitAddUser() {
          this.$refs['addUserForm'].validate(valid=>{
            if(valid) {
              insertUser(this.addUser).then(res=>{
                if(res.data.code === 200) {
                  this.$message.success('添加成功')
                  this.getUserList()
                }
              })
            }
          })
        },
        //清空添加用户表单
        resetAddUser() {
          this.$refs['addUserForm'].resetFields();
        },
        //提交更新用户
        submitEditorUser() {
          this.$refs['editorUserForm'].validate(valid=>{
            if(valid) {
              updateUser(this.editorUser).then(res=>{
                if(res.data.code === 200) {
                  this.$message.success('更新成功')
                  this.isEditorDialog = false
                  this.getUserList()
                }
              })
            }
          })
        },
        //初始化角色选择器
        initSelectRole() {
          getSelectRole().then(res=>{
            this.roleOptions = res.data.data.role_select
          })
        },
        //初始化部门选择器
        initSelectDept() {
          this.$store.dispatch('getSelectDepartmentTree').then(deptTree=>{
            this.deptOptions = deptTree
          })
        }
      },
      mounted() {
        this.getUserList()
        this.initSelectRole()
        this.initSelectDept()
      }
    }
</script>

<style lang="scss" scoped>
  .user-container {
    background-color: #fff !important;
    padding: 10px;

    .search {
      margin-bottom: 10px;
    }
    .table-container {
      width: 200px;
    }
  }
</style>
